﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SmApiLibrary.libs;
using CM = System.Configuration.ConfigurationManager;
using SmAp.Operator.OP.ABF;
using SmAp.Operator.Interface;
using SmApiLibrary.datatypes.Interface;
using SmApiLibrary.datatypes.AbstarctFactory;
using SmApiLibrary.helps;
using Teein.LiNing.BLL;
using SmApiLibrary.Err;
using System.Web.SessionState;

namespace Teein.H2O.Web
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    public class AccountHandler : IHttpHandler,IRequiresSessionState
    {
        public readonly string APPKEY = CM.AppSettings["APPKEY"];
        public readonly string APPSECRET = CM.AppSettings["APPSECRET"];

        public WeiBoType WeiBoType
        {
            get;
            set;
        }

        public void ProcessRequest(HttpContext context)
        {
            //获取请求回传的微博类型参数
            string type = context.Request.QueryString["Type"];
            WeiBoType = (WeiBoType)Enum.Parse(typeof(WeiBoType), type, true);
            IWeiBo wb = WeiboFactory.CreateWeiBoByType(WeiBoType);
            OAuthBase oauth = wb.GetOAuth();
            oauth.ConsumerKey = APPKEY;
            oauth.ConsumerSecret = APPSECRET;

            context.Response.ContentType = "text/plain";
            string action = context.Request.QueryString["Action"];
            switch (action)
            {
                case "login":
                    SinaLoginAction(context,oauth);
                    break;
                case "verifier":
                    GetUserAction(context, oauth);
                    break;
            }
        }

        protected void SinaLoginAction(HttpContext context, OAuthBase oauth)
        {
            string url = context.Request.UrlReferrer.ToString();


            string getUrl = oauth.AuthorizationLinkGet();
            context.Session.Add("oauth_token", oauth.Token);
            context.Session.Add("oauth_token_secret", oauth.TokenSecret);

            context.Response.Write(getUrl + "&oauth_callback=" + url);
        }

        protected void GetUserAction(HttpContext context, OAuthBase oauth)
        {
            if (context.Session["oauth_token"] != null)
            {
                oauth.Token = context.Session["oauth_token"].ToString();
                oauth.TokenSecret = context.Session["oauth_token_secret"].ToString();
            }

            if (string.IsNullOrEmpty(oauth.Verifier) || context.Session["oauth_verifier"] == null)
            {
                oauth.Verifier = context.Request.QueryString["oauth_verifier"];
                context.Session["oauth_verifier"] = oauth.Verifier;
            }

            try
            {
                oauth.AccessTokenGet(context.Request.QueryString["oauth_token"], context.Request.QueryString["oauth_verifier"]);
                context.Session["oauth_token"] = oauth.Token;
                context.Session["oauth_token_secret"] = oauth.TokenSecret;

                IOAuth oauthOP = OperatorABF.CreateAbstractFactory(WeiBoType).CreateOAuth();
                string str = oauthOP.GetUser(oauth);
                IUser user = DataTypeABF.CreateFactory(WeiBoType).CreateUser();
                user = JsonHelper.JsonDeserialize<IUser>(str);

                string errorMsg = string.Empty;
                AccountBLL bll = new AccountBLL();
                bll.InsertAccount(user, oauth);
                context.Session["User"] = user;
                context.Response.Write("sucess");
            }
            catch (System.Web.HttpRequestValidationException vex)
            {
                context.Response.Write("{'failed':'1','msg':'授权异常，请更换账号'}");
            }
            catch (WeiBoRequestException ex)
            {
                context.Response.Write("{'failed':'1','msg':'授权异常，请更换账号'}");
            }
            catch (System.Data.SqlClient.SqlException dex)
            {
                context.Response.Write("{'failed':'1','msg':'该账号已存在，不得重复添加'}");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
